package com.meiqiongproperty.yiguanjia.fragment.home.health;

import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.activity.GenericFragmentActivity;
import com.meiqiongproperty.yiguanjia.commom.ViewConstant;
import com.meiqiongproperty.yiguanjia.databinding.HealthyShopDetailLayoutBinding;
import com.meiqiongproperty.yiguanjia.fragment.BaseFragment;
import com.meiqiongproperty.yiguanjia.fragment.home.shopping.bean.ShopLocalListBean;
import com.meiqiongproperty.yiguanjia.http.api.ApiService;
import com.meiqiongproperty.yiguanjia.http.interfaces.SimpleHttpCallback;
import com.meiqiongproperty.yiguanjia.http.sendJsonModel.SendShopDetail;
import com.meiqiongproperty.yiguanjia.httpbean.shopping.ShopDetailBean;
import com.meiqiongproperty.yiguanjia.ui.SlidingDetailsLayout;
import com.meiqiongproperty.yiguanjia.ui.adbanner.animations.DescriptionAnimation;
import com.meiqiongproperty.yiguanjia.ui.adbanner.indicators.PagerIndicator;
import com.meiqiongproperty.yiguanjia.ui.adbanner.slidertypes.BaseSliderView;
import com.meiqiongproperty.yiguanjia.ui.adbanner.slidertypes.TextSliderView;
import com.meiqiongproperty.yiguanjia.ui.adbanner.viewpagerswitchanimation.SliderLayout;
import com.meiqiongproperty.yiguanjia.ui.popupWindow.ProductDetailBuyPopupWindow;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * author: Administrator
 * date: 2017/5/21.
 * package:com.meiqiongproperty.yiguanjia.fragment.home.health
 */

public class HealthyShopDetailFragment extends BaseFragment {

    HealthyShopDetailLayoutBinding binding;
    ProductDetailBuyPopupWindow popupWindow;
    int sum = 1;
    String productId = "";
    List<String> list_image = new ArrayList<>();
    ShopDetailBean.ShopinfoBean shop_info;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.healthy_shop_detail_layout, container, false);
        binding.setClick(this);
        savedInstanceState = getArguments();
        if (savedInstanceState != null) {
            productId = savedInstanceState.getString("productId");
        }

        // getData1();
        initWebView();
        initView();
        getDetailData();
        return binding.getRoot();
    }

    public void getData1(final List<String> img) {
        if (isAdded()) {
            binding.slider.getPagerIndicator().setDefaultIndicatorColor(getActivity().getResources().getColor(R.color.transparent), Color.argb(1, 255, 255, 255));
        }

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.slider.stopAutoCycle();
            }
        }, 200);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (img.size() <= 1) {
                    binding.slider.setBottomIndicator(View.GONE);
                    binding.slider.getPagerIndicator().setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Invisible);
                } else {
                    binding.slider.setBottomIndicator(View.VISIBLE);
                    binding.slider.getPagerIndicator().setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Visible);
                    if (isAdded()) {
                        binding.slider.getPagerIndicator().setDefaultIndicatorColor(getActivity().getResources().getColor(R.color.header_color), Color.argb(66, 255, 255, 255));
                    }
                }

                if (img.size() <= 1) {
                    binding.slider.stopAutoCycle();
                } else {
                    binding.slider.startAutoCycle();
                }
            }
        }, img.size() * 1000);
        for (int i = 0; i < img.size(); i++) {
            TextSliderView textSliderView = new TextSliderView(getActivity(), img);
            // initialize a SliderLayout
            textSliderView
                    .image(img.get(i))
                    .setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                        @Override
                        public void onSliderClick(BaseSliderView slider) {

                        }
                    });

            binding.slider.addSlider(textSliderView);
        }
        // binding.customIndicator.setColor(Color.rgb(19, 181, 221),Color.argb(33, 255, 255, 255));
        binding.slider.setPresetTransformer(SliderLayout.Transformer.Stack);
        binding.slider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        binding.slider.setCustomAnimation(new DescriptionAnimation());

    }

    public void healthy_shop_purchase(View view) {
        showPopwindow();
    }


    public void showPopwindow() {
        binding.cover.setVisibility(View.VISIBLE);
        popupWindow = new ProductDetailBuyPopupWindow(getActivity());
        popupWindow.setBackgroundDrawable(null);

        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        popupWindow.showAtLocation(binding.detailBuy, Gravity.BOTTOM
                , 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.cover.setVisibility(View.GONE);
            }
        });

        final EditText et_amount = (EditText) popupWindow.getContentView().findViewById(R.id.et_amount);

        popupWindow.getContentView().findViewById(R.id.increase).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sum++;
                et_amount.setText(sum + "");
                Utils.sectionAfter(et_amount);
            }
        });

        popupWindow.getContentView().findViewById(R.id.decrease).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sum--;
                et_amount.setText(sum + "");
                Utils.sectionAfter(et_amount);
            }
        });

        popupWindow.getContentView().findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewConstant.list_local_shop.clear();
                ShopLocalListBean bean = ViewConstant.shopBean;
                bean.clear();
                bean.setProduct_count(sum);
                bean.setProduct_id(productId);
                bean.setProduct_oprice(Double.parseDouble(shop_info.getOprice()));
                bean.setProduct_price(Double.parseDouble(shop_info.getPrice()));
                bean.setProduct_title(shop_info.getProductName());
                bean.setProduct_image(list_image.get(0));
                ViewConstant.list_local_shop.add(bean);

                GenericFragmentActivity.start(getActivity(), HealthyConfirmOrderFragment.class, new Bundle());
                popupWindow.dismiss();
            }
        });

        popupWindow.getContentView().findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 请求用户详情数据
     */
    public void getDetailData() {
        SendShopDetail detail = new SendShopDetail();
        detail.setToken(Utils.getToken(getActivity()));
        detail.setProductId(productId);
        ApiService.getShopDetail(getActivity(), new SimpleHttpCallback<ShopDetailBean>() {
            @Override
            public void onNext(ShopDetailBean shopDetailBean) {
                Gson gson = new Gson();
                LogUtil.d("shopDetail==================>" + gson.toJson(shopDetailBean));
                //轮播图数据
                list_image.clear();
                list_image.addAll(shopDetailBean.getShopimage());
                List<String> images = new ArrayList<String>();
                for (int i = 0; i < shopDetailBean.getShopimage().size(); i++) {
                    images.add(shopDetailBean.getShopimage().get(i));
                }
                getData1(images);
                binding.webview.loadUrl(shopDetailBean.getShopinfo().getDesc());

                //商品详情信息
                shop_info = shopDetailBean.getShopinfo();
                binding.healthyShopDetailName.setText(shop_info.getProductName());
                binding.healthyShopDetailPrice.setText("￥" + shop_info.getPrice());
                binding.tvBusinessName.setText(shop_info.getBusinessName());
                binding.healthyDetailContent.setText(shop_info.getRemark());
                binding.healthyProductAfterPrice.setText("￥" + shop_info.getOprice());
            }

            @Override
            public void onError(int code, String message) {
                super.onError(code, message);
            }
        }, Utils.getRequestBody(detail));
    }


    private void initWebView() {
        WebSettings settings = binding.webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        binding.webview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        settings.setDomStorageEnabled(true);// 设置可以使用localStorage
        binding.webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        binding.webview.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                //这句话说的意思告诉父View我自己的事件我自己处理
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        binding.webview.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String scheme = url.substring(0, 4).trim().toLowerCase();
                if (scheme.contains("https") || scheme.contains("http")) {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                int w = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                int h = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                //重新测量
                binding.webview.measure(w, h);
            }
        });
    }

    private void initView() {
        binding.tishi.setText("上拉查看商品详情");
        binding.slidingDetailsLayout.setPositionChangListener(new SlidingDetailsLayout.PositionChangListener() {
            @Override
            public void position(int positon) {
                if (positon == 0) {
                    binding.tishi.setText("上拉查看商品详情");
                } else {
                    binding.tishi.setText("下拉返回商品简介");

                }
            }

            @Override
            public void onBottom() {
                binding.tishi.setText("松开，马上加载商品详情");
            }

            @Override
            public void backBottom() {
                binding.tishi.setText("上拉查看商品详情");
            }

            @Override
            public void onTop() {
                binding.tishi.setText("松开，返回商品简介");
            }

            @Override
            public void backTop() {
                binding.tishi.setText("下拉返回商品简介");
            }
        });
    }
}
